package com.websql.yousql.config.dataSource;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.HashMap;

@Slf4j
@Component
@Data
public class DataSourceProviderImpl implements DataSourceProvider {

    public static HashMap<String,String> hostAndPort = new HashMap<>();
    @Value("${my.datasource.username}")
    private String userName;
    @Value("${my.datasource.password}")
    private String password;
    @Value("${my.datasource.databasename.suffix}")
    private String databaseSuffix;
    @Value("${my.datasource.host}")
    private String host;
    @Value("${my.datasource.port}")
    private Integer port;

    @Override
    public DataSource createDataSourceByBotCode(String dbName) {
        try {
            if(!"queryDB".equals(dbName)){
                dbName = "/"+dbName;
            }else {
                dbName = "";
            }
            hostAndPort.put("host",host);
            hostAndPort.put("port",String.valueOf(port));
            return DataSourceBuilder.create()
                    .url("jdbc:mysql://" + host + ":" + port + dbName /*+ databaseSuffix*/ + "?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true")
                    .driverClassName("com.mysql.cj.jdbc.Driver")
                    .username(userName)
                    .password(password)
                    .build();
        } catch (Exception e) {
            log.error("DataSourceProviderImpl createDataSourceByBotCode error", e);
        }
        return null;
    }

}
